#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string>
#include<cstring>

void Usage(std::string proc)
{
    std::cerr <<"Usage: " << proc << "serverip serverport" << std::endl;
}

//udp_client server_ip server_port
int main(int argc , char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //创建套接字
    //sock  #include<sys/sockrt.h> int socket(int domain, int type, int protocol); ,返回值为文件描述符
    // AF_INET SOCK_DGRAM  sock_dgram
    int sockfd = socket(AF_INET , SOCK_DGRAM , 0);
    if(sockfd < 0)
    {
        std::cout<< "create socket error" << std::endl;
        return 0;
    }
    //客户端一般知道服务器的信息
    struct sockaddr_in server;
    memset(&server , 0 , sizeof(server));//将结构体server 置空
    //填写数据
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while(true)
    {
        std::cout<< "Please Emter@ ";
        std::string line;
        std::getline(std::cin , line);

        //客户将数据写入
        sendto(sockfd , line.c_str() , line.size() , 0 , (struct sockaddr*)&server , sizeof(server));

        //客户端读
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];//将读取的数据放在buffer中
        int m = recvfrom(sockfd , buffer , sizeof(buffer) , 0, (struct sockaddr*)&temp , &len);
        //recvfrom 返回读取到的字节数
        if(m>0)
        {
            buffer[m] = 0;
            std::cout<< buffer << std::endl;
        }
    }
    return 0;
}